/**
 * 房间数据模型
 * 
 * @author LuoDong
 * @email luo4521@online.net.tw
 * 2010-2-5 14:53
 */
package com.addcn.texas.model
{
	import it.gotoandplay.smartfoxserver.SmartFoxClient;
	import it.gotoandplay.smartfoxserver.SFSEvent;
	
	import com.addcn.fog.model.Model;
	import com.addcn.fog.model.ModelLocator;
	import com.addcn.fog.control.Controller;
	import com.addcn.common.utils.Server;
	import com.addcn.texas.utils.DataResolve;	
	import com.addcn.texas.data.*;
	
	public class HallModel extends Model 
	{
		public static const UPDATA_ROOMS : String = "updateRooms";	
		public static const HALL_DATA_REDY: String = "hallDataRedy";
		public static const HALLS_NAME : String = "hallsName";
		public static const UPDATA_TABLE : String = "updataTable";
		public static const JOIN_ROOM_OK : String = "joinRoomOk";
		public static const JOIN_ROOM_ERR: String = "joinRoomErr";
				
		private var _server : SmartFoxClient
		private var _hall_data : HallData;
		private var _roomList : Object ;
		private var _hallList : Object ;
		private var _roomCount : Object;
		private var _list_type: int;

		public function HallModel() : void {
			_initialize();						
		}
		
		private function _initialize() : void 
		{
			_hall_data = HallData.getInstance();
			_roomList  = {};
			_roomCount = { };
			_hallList  = _hall_data.getData("hallList") == null ? null : _hall_data.getData("hallList");
		
			if( _hallList != null){
				sendNotification(HALLS_NAME, this._hallList);
			}
			_server = Server.getInstance();			
			_server.addEventListener(SFSEvent.onExtensionResponse, _responseHandler);				
		}
		
		/**
		 * 對外公開方法,根據大廳類型獲取房間列表
		 * @param	r_type    String 大廳類型
		 * @param	r_request Boolean 是否請求服務端數據,默認false
		 */
		public function getRoomList(r_type : int = 0, r_request :Boolean = false) : void
		{
			if (r_type == 0) {
				r_type = _calculateType();
			}
			if ( !r_request && HallData.getInstance().getData(r_type) ) {
				//獲取本地數據
				_upDateRoomList(r_type);									
			}else { 
				//請求服務端				
				var _data : Object = { };
				_data.type = r_type;
				_data.ac = "getRoomList";
				_server.sendXtMessage(Server.ext(0), "roomAc", _data, SmartFoxClient.XTMSG_TYPE_JSON);
			}
		}
		
		private function _calculateType( ) : int
		{			
			var _level : int = MyUser.getInstance().level;	
			if (_level <= 10 ) {
				return 1;
			}else if (_level <= 20) {
				return 2;
			}else if (_level <= 30) {
				return 3;
			}else if (_level <= 40) {
				return 4;
			}else {
				return 5;
			}
		}
				
		/**
		 * 對外公開方法,進入房間
		 * @param	r_type String 大廳類型
		 * @param	r_id String   房間ID
		 */
		public function joinRoom(r_type: int , r_id : String) : void
		{
			if (!ModelLocator.getInstance().hasModel(UserInfoModel)) {
				sendNotification(JOIN_ROOM_ERR, { code:"9995" } );	
				return;
			}
			
			//var _user_info = ModelLocator.getInstance().getModel(UserInfoModel).getUserInfo();
			//
			//if (_user_info["id"] == null) {
				//sendNotification(JOIN_ROOM_ERR, { code:"9995" } );	
				//return;
			//}
			//var _id : int = MyUser.getInstance().user.id;
			
			var _data = HallData.getInstance().getData(r_type);			
			if (_data != null) {
				var _param : Object = { };
				_param.rid = _data[r_id]["id"];
				_param.ac = "joinRoom";
				_server.sendXtMessage(Server.ext(0), "roomAc", _param, SmartFoxClient.XTMSG_TYPE_JSON);			
			}
		}
		
		private function _responseHandler(evt : SFSEvent) : void {
			var _data = evt.params.dataObj.dataObj;		
			switch(evt.params.dataObj._cmd) {
				case "loginOk":	
					_setHallList(_data);
					getRoomList(2, true);	
					break;
				case "getRoomList":
					_resolveRoomList(_data);  //解析數據
					var _type : int = _data.type;					
					_upDateRoomList(_type);
					break;
				case "joinRoom":				
					var _obj : Object;
					if (_data.err != 0) { //進入房間失敗
						if (_data.err == 7777) {
							_obj = _resolveJoinRoom(_data.r);
							sendNotification (UPDATA_TABLE, _obj);
						}else {													
							//sendNotification(JOIN_ROOM_ERR, {code:data.err});							
						}
						return;	
					}	
					//if (_data.r == null) return;
					//_obj = _resolveJoinRoom(_data.r);
					//_data.r = _obj;
					//_server.activeRoomId = _obj["id"];					
					sendNotification(JOIN_ROOM_OK, _data);		
					_setGameModelData(_data);
					break;					
			}
		}
		
		/**
		 * 大厅游戲場数据
		 * @param	r_data
		 */
		private function _setHallList(r_data : Object) : void
		{			
			this._hallList = this._hallList == null ? { } : this._hallList;
			if (r_data == null) return ;
			var _dr = DataResolve.getInstance();
			var _i : int = 0;
			for each(var _val in r_data.hall) {
				this._hallList[_i] = _dr.ResolveHallType(_val);				
				_i++;
			}			
			HallData.getInstance().setData("hallList", this._hallList);	 //存入數據對象
			sendNotification(HALLS_NAME, this._hallList); //發生通知,傳遞游戲場類別數據
		}
				
		/**
		 * 解析游戲房间數據
		 * @param	r_data Object
		 */
		private function _resolveRoomList(r_data : Object) : void 
		{						
			var _rooms : Array = r_data.data;					
			var _type : int = r_data.type;						
			var _list_obj : Object = { };			
			var _count : int = 0; 
			for each(var _val in _rooms) 
			{
				_list_obj[_val[0]] = DataResolve.getInstance().ResolveRoom(_val);  //解析房間列表數據
				_count++;		
			}						
			HallData.getInstance().setData(_type, _list_obj);  //存入數據對象
			//this._roomList[_type] = _list_obj;		
			this._roomCount[_type] = _count;	
		}
		
						
		//解析進入當前房間的數據
		private function _resolveJoinRoom(r_data : Object) : Object
		{
			var _redata = DataResolve.getInstance().ResolveJoinRoom(r_data);
			var _room : Object = this._roomList[this._list_type][r_data[0]];	
			_room = _redata;			
			return this._roomList[this._list_type][r_data[0]];						
		}
		
		/**
		 * 發送通知，更新房間列表數據
		 * @param	r_type int
		 */
		private function _upDateRoomList(r_type : int) : void
		{				
			this._list_type = r_type;	
			var _list : Object = HallData.getInstance().getData(r_type);			
			MonsterDebugger.trace("_updateRoomList", [_list,r_type])
			sendNotification(UPDATA_ROOMS, { roomList:_list, roomCount:this._roomCount[r_type] , type:r_type } );	
		}
		
		/**
		 * 设置游戏model数据
		 * @param	r_data Object
		 */
		private function _setGameModelData(r_data : Object) : void
		{
			var _model : Object;
			var _modelLocator = ModelLocator.getInstance();
			//設置房間數據
			if (_modelLocator.hasModel(RoomModel)) {										
				_model = _modelLocator.getModel(RoomModel);	
				_model.setRoomData(r_data.r);  	
			}				
			
			//設置房間中玩家數據	
			if(_modelLocator.hasModel(RoomUserModel)){
				_model = _modelLocator.getModel(RoomUserModel);		
				var _obj = { u:r_data.u };  //u:玩家數據,s:座位對應表
				_model.setRoomUserData(_obj);  
			}
			
			//設置游戏數據	
			if (_modelLocator.hasModel(GameInfoModel)) {											
				_model = _modelLocator.getModel(GameInfoModel);							
				_model.setGameData(r_data.g); 											
			}	
		}
			
		override public function destroy():void 
		{	
			_server.removeEventListener(SFSEvent.onExtensionResponse, _responseHandler);
			this._roomList = null;
			this._hallList = null;
			this._roomCount = null;
		}
	}
	
}
